import {
  postTokenPhoneRegister,
  postTokenSendsms,
  postLoginAccessToken,
  putUsersMe,
  getUserMeAPI,
} from '@/services/member'
import { loginTypeEnum, purposeEnum } from '@/types/constants'
import type { LoginResult, ProfileUpdate } from '@/types/members'
import { defineStore } from 'pinia'
import { ref } from 'vue'

// 定义 Store
export const useMemberStore = defineStore(
  'member',
  () => {
    //发送验证码
    const sendVerificationCode = async (phone: string, purpose: purposeEnum) => {
      postTokenSendsms(phone, purpose)
    }
    // 手机号注册
    const phoneRegister = async (phone: string, password: string, verification_code: string) => {
      postTokenPhoneRegister(phone, password, verification_code)
    }
    // 手机号登录
    const LoginAccessToken = async (phone: string, password: string, login_type: loginTypeEnum) => {
      const res = await postLoginAccessToken(phone, password, login_type)
      setProfile(res.data)
    }
    // 会员信息
    const profile = ref<LoginResult>()

    // 保存会员信息，登录时使用
    const setProfile = (val: LoginResult) => {
      // 合并更新的数据到现有的 profile

      profile.value = {
        ...profile.value,
        ...val,
      }
    }

    // 清理会员信息，退出时使用
    const clearProfile = () => {
      profile.value = undefined
    }

    // 更新用户信息
    const updateProfile = async (data: ProfileUpdate) => {
      const res = await putUsersMe(data)
      setProfile(res.data)
    }
    // 获取用户信息
    const getUserMe = async () => {
      const res = await getUserMeAPI()
      setProfile(res.data)
    }

    // 记得 return
    return {
      profile,
      phoneRegister,
      LoginAccessToken,
      clearProfile,
      sendVerificationCode,
      updateProfile,
      getUserMe,
    }
  },
  // TODO: 持久化
  {
    persist: {
      storage: {
        setItem(key, value) {
          uni.setStorageSync(key, value)
        },
        getItem(key) {
          return uni.getStorageSync(key)
        },
      },
    },
  },
)
